package com.example.music_players

import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.Binder
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log
import java.util.*

class MusicService : Service() {
    companion object {
        const val COMMAND = "Operate"
    }
    val TAG = "MusicService"
    val mediaPlayer = MediaPlayer()
    val musicList = mutableListOf<String>()
    val musicNameList = mutableListOf<String>()
    var current = 0
    var isPause = false
    val binder = MusicBinder()

    inner class MusicBinder : Binder() {
        val size: Int
            get() = musicList.size
        val musicName: String
            get() = musicNameList[current]
        var currentPosition: Int
            get() = mediaPlayer.currentPosition
            set(value) = mediaPlayer.seekTo(value)
        val duration: Int
            get() = mediaPlayer.duration
        val currentIndex: Int
            get() = current
    }

    override fun onCreate() {
        super.onCreate()
        getMusicList()

        mediaPlayer.setOnPreparedListener {
            it.start()
        }
        mediaPlayer.setOnCompletionListener {
            current++
            if (current >= musicList.size) {
                current = 0
            }
            play()
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val operate = intent?.getIntExtra(COMMAND, 1) ?: 1
        when (operate) {
            1 -> play()
            2 -> pause()
            3 -> stop()
            4 -> next()
            5 -> prev()
        }

        return super.onStartCommand(intent, flags, startId)
    }

    fun pause() {
        if (isPause) {
            mediaPlayer.start()
            isPause = false
        } else {
            mediaPlayer.pause()
            isPause = true
        }
    }

    fun stop() {
        mediaPlayer.stop()
        stopSelf()
    }

    fun next() {
        current++
        if (current >= musicList.size) {
            current = 0
        }
        play()
    }

    fun prev() {
        current--
        if (current < 0) {
            current = musicList.size - 1
        }
        play()
    }

    fun play() {
        if (musicList.isEmpty()) return
        val path = musicList[current]
        mediaPlayer.reset()
        try {
            mediaPlayer.setDataSource(path)
            mediaPlayer.prepareAsync()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onBind(intent: Intent): IBinder {
        return binder
    }

    private fun getMusicList() {
        val cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null)
        if (cursor != null && cursor.moveToFirst()) {
            val musicPathIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA)
            val musicNameIndex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)

            // 检查索引是否有效
            if (musicPathIndex == -1 || musicNameIndex == -1) {
                Log.e(TAG, "Column index not found.")
                cursor.close()
                return
            }

            do {
                val musicPath = cursor.getString(musicPathIndex)
                val musicName = cursor.getString(musicNameIndex)
                musicList.add(musicPath)
                musicNameList.add(musicName)
            } while (cursor.moveToNext())

            cursor.close()
        } else {
            Log.e(TAG, "Query returned no results.")
        }
    }
}